package com.lg.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.FileInfo;
import org.csource.fastdfs.ServerInfo;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import com.lg.pojo.FastDFSFile;

public class FastDFSClient {

	private static Logger logger = LoggerFactory.getLogger(FastDFSClient.class);
	private static TrackerClient trackerClient;
	private static TrackerServer trackerServer;
	private static StorageServer storageServer;
	private static StorageClient storageClient ;
	static {

		try {
			String conf_filename = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
			ClientGlobal.init(conf_filename);
			trackerClient = new TrackerClient();
			trackerServer = trackerClient.getConnection();
			storageServer = trackerClient.getStoreStorage(trackerServer);

		} catch (Exception e) {
			logger.info("fastDFS  init faile");
		}

	}

	public static String[] upload(FastDFSFile file) {
	    logger.info("File Name: " + file.getName() + "File Length:" + file.getContent().length);

	    NameValuePair[] meta_list = new NameValuePair[1];
	    meta_list[0] = new NameValuePair("author", file.getAuthor());
	    long startTime = System.currentTimeMillis();
	    String[] uploadResults = null;
	    try {
	    	 storageClient = new StorageClient(trackerServer, storageServer);
	        uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
	    } catch (IOException e) {
	        logger.error("IO Exception when uploadind the file:" + file.getName(), e);
	    } catch (Exception e) {
	        logger.error("Non IO Exception when uploadind the file:" + file.getName(), e);
	    }
	    logger.info("upload_file time used:" + (System.currentTimeMillis() - startTime) + " ms");
	    if (uploadResults == null) {
	        logger.error("upload file fail, error code:" + storageClient.getErrorCode());
	    }
	    String groupName = uploadResults[0];
	    String remoteFileName = uploadResults[1];
	    logger.info("upload file successfully!!!" + "group_name:" + groupName + ", remoteFileName:" + " " + remoteFileName);
	    return uploadResults;
	}
	
	/**
	 * 根据groupName和文件名获取文件信息。
	 * @param groupName
	 * @param remoteFileName
	 * @return
	 */
	public static FileInfo getFile(  String groupName,String remoteFileName) {
		StorageClient storageClient2 = new StorageClient(trackerServer, storageServer);
		try {
			return  storageClient2.get_file_info(groupName, remoteFileName);
		} catch (Exception e) {
			logger.error("Get FileInfo from Fast DFS failed "+ e);
		}
		return null;
	}
	/**
	 * 以字节的形式下载文件
	 * @param groupName
	 * @param remoteFileName
	 * @return
	 */
	public static byte[]  downFile(String groupName,String remoteFileName) {
		StorageClient storageClient2 = new StorageClient(trackerServer, storageServer);
		try {
			byte[] download_file = storageClient2.download_file(groupName, remoteFileName);
		   return download_file;
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("down File from Fast DFS failed " +e);
		} catch (MyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("down File from Fast DFS failed " +e);
		}
		return null;
	}
	
	/**
	 * 以流的形式下载文件
	 * @param groupName
	 * @param remoteFileName
	 * @return
	 */
	public static InputStream downfile1(String groupName,String remoteFileName) {
		byte[] downFile = downFile(groupName, remoteFileName);
		
		if(downFile == null) {
			return null;
		}else {
			return new ByteArrayInputStream(downFile);
		}
	}
	
	/**
	 * 删除storage上的文件
	 * @param groupName
	 * @param remoteFileName
	 * @return
	 */
	public static boolean  deleteFile(String groupName,String remoteFileName) {
		StorageClient storageClient2 = new StorageClient(trackerServer, storageServer);
		try {
			int delete_file = storageClient2.delete_file(groupName, remoteFileName);
			if(delete_file == 0) {
				return true;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("delete File faile : "+ e);
		}
		return false;
	}
	/**
	 * 
	 * @return
	 * @throws IOException
	 */
	public static String getTrackerUrl() throws IOException {
		return "http://"+trackerServer.getInetSocketAddress().getHostString()+":"+ClientGlobal.getG_tracker_http_port()+"/";
	}
	
	public static StorageServer[] getStoreStorages(String groupName)
			throws IOException {
		return trackerClient.getStoreStorages(trackerServer, groupName);
	}

	public static ServerInfo[] getFetchStorages(String groupName,
												String remoteFileName) throws IOException {
		return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
	}

}
